import * as DominConfigs from "../constants/domin-constants";
import { message } from "antd";

/**
 * request日志
 * @param config
 */
export const requestLog = (config: any) => {
  console.log("Request <<<<<<<<<<<<<<<<<<<<<<<");
  console.dir(config);
  console.log("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
};

/**
 * response日志
 * @param response
 */
export const responseLog = (response: any) => {
  console.log("Response >>>>>>>>>>>>>>>>>>>>>>");
  console.dir(response);
  console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
};

/**
 * request 守卫（主要用于鉴权）
 * @param request
 */
export const requestAuthorization = (request: any) => {
  // console.log("axios request拦截器");
  if (localStorage.getItem("Authorization")) {
    // console.log("加响应头");
    request.headers.Authorization = localStorage.getItem("Authorization");
    return request;
  } else {
    return request;
  }
};

/**
 * 响应错误时显示对应msg
 * @param error 错误
 * @param router
 */
export const responseErrorMessage = (error: any, router: any) => {
  // console.log("axios response 拦截器");
  const errorStatus = error.response.status;
  const { msg } = error.response.data;
  if (errorStatus === DominConfigs.RESPONSE_CODE.error) {
    // 客户端请求失败400
    if (msg) {
      message.error(msg);
    }
  } else if (errorStatus === DominConfigs.RESPONSE_CODE.unauthorized) {
    // 客户端请求失败401
    message.warning("身份认证失效,请重新登录");
    localStorage.clear();
    router.push("/");
  } else if (errorStatus === DominConfigs.RESPONSE_CODE.unFind) {
    // 客户端请求失败404
    if (msg) {
      message.error(msg);
      router.push("/");
    }
  } else if (errorStatus === DominConfigs.RESPONSE_CODE.serviceError) {
    // 服务器解析错误500
    message.error("服务器内部异常，请稍后再试");
  }
};
